package com.dsmusic.musicpro.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.dsmusic.musicpro.pojo.Detail;
import com.dsmusic.musicpro.pojo.Lyric;
import com.dsmusic.musicpro.pojo.Music;
import org.jsoup.Jsoup;

import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class MusicServiceImpl implements MusicService {

    // 查找音乐，返回List音乐集合
    @Override
    public List<Music> searchMusic(String key, String page) {

        String url = "http://www.kuwo.cn/api/www/search/searchMusicBykeyWord?key=" + key + "&pn=" + page + "&rn=15&httpsStatus=1&reqId=a438ee51-c2ac-11eb-9c79-75c6cbf2f941";

        String str =
                null;
        try {
            str = Jsoup.connect(url)
                    .cookie("kw_token", "wow")
                    .header("csrf", "wow")
                    .header("Referer", "http://www.kuwo.cn/")
                    .ignoreContentType(true)
                    .get()
                    .text();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String data = JSON.parseObject(str).getString("data");
        String list = JSON.parseObject(data).getString("list");
        List<Music> musics = JSON.parseArray(list, Music.class);

        for (int i = 0; i < musics.size(); i++) {
            Music music = musics.get(i);
            music.setUrl(getMusicUrl(music.getRid()));
            if (new MusicServiceImpl().getLyric(music.getRid()) == null) {
                musics.remove(music);
            }
        }

        return musics;
    }

    // 获取音乐的mp3链接
    @Override
    public String getMusicUrl(String rid) {
        String format_url = "http://www.kuwo.cn/url?format=mp3&rid=" + rid + "&response=url&type=convert_url3&br=128kmp3&from=web&t=1622512069271&httpsStatus=1&reqId=5ed51180-c27b-11eb-ad29-8938c4d7ab51";

        String str = null;
        try {
            str = Jsoup.connect(format_url).get().text();
        } catch (IOException e) {
            e.printStackTrace();
        }

        String url = JSON.parseObject(str).getString("url");
        return url;
    }

    // 获取MV的链接
    @Override
    public String getMvUrl(String rid) {
        String format_url = "http://www.kuwo.cn/url?rid=" + rid + "&response=url&format=mp4%7Cmkv&type=convert_url&t=1622538188854&httpsStatus=1&reqId=2f50fd60-c2b8-11eb-b5e3-e34961c79845";

        String url = null;
        try {
            url = Jsoup.connect(format_url).get().text();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return url;
    }

    // 下载音乐或者MV
    @Override
    public void download(String mp_url, String name) {
        mp_url = mp_url.replace("https", "http");

        // 创建统一资源定位符
        URL url = null;
        try {
            url = new URL(mp_url);

            // 创建输入输出流
            InputStream is = url.openStream();
            OutputStream os = new FileOutputStream("d:\\Music\\" + name + mp_url.substring(mp_url.lastIndexOf(".")));

            // 边读边写，实现下载
            byte[] bytes = new byte[1024];
            while (true) {
                int read = is.read(bytes);
                if (read == -1) {
                    break;
                }
                os.write(bytes, 0, read);
            }

            // 关闭输出输入流
            os.close();
            is.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 获取歌词以及时间点，返回List歌词集合
    @Override
    public List<Lyric> getLyric(String rid) {
        String url = "http://m.kuwo.cn/newh5/singles/songinfoandlrc?musicId=" + rid;

        int islyric = 1;
        List<Lyric> lyrics = null;
        try {
            String str = Jsoup.connect(url).get().text();

            char ch = str.charAt(19);

            if (ch == 'n') {
                islyric = 0;
                return null;
            } else {
                String data = JSON.parseObject(str).getString("data");
                String lrclist = JSON.parseObject(data).getString("lrclist");

                lyrics = JSON.parseArray(lrclist, Lyric.class);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return lyrics;
    }

    // 获取歌曲详情页面信息
    @Override
    public Detail getDetail(String rid) {
        String url = "http://www.kuwo.cn/api/www/music/musicInfo?mid=" + rid + "&httpsStatus=1&reqId=9a5e6b70-c983-11eb-9340-a39c53f32cfc";

        String str = null;
        Detail detail = null;
        try {
            str = Jsoup.connect(url)
                    .cookie("kw_token", "wow")
                    .header("csrf", "wow")
                    .header("Referer", "http://www.kuwo.cn/")
                    .ignoreContentType(true)
                    .get()
                    .text();

            String data = JSON.parseObject(str).getString("data");

            String name = JSON.parseObject(data).getString("name");
            String artist = JSON.parseObject(data).getString("artist");
            String pic = JSON.parseObject(data).getString("pic");
            String hasmv = JSON.parseObject(data).getString("hasmv");
            String albuminfo = JSON.parseObject(data).getString("albuminfo");

            String mp3Url = new MusicServiceImpl().getMusicUrl(rid);
            String mp4Url;

            // 判断歌曲是否有MV
            if (hasmv.equals("1")) {
                mp4Url = new MusicServiceImpl().getMvUrl(rid);
            } else {
                mp4Url = null;
            }

            detail = JSON.parseObject(data, Detail.class);

            // 封装成Detail类
            detail.setName(name);
            detail.setArtist(artist);
            detail.setPic(pic);
            detail.setMp3Url(mp3Url);
            detail.setMp4Url(mp4Url);
            detail.setHasmv(hasmv);


        } catch (Exception e) {
            e.printStackTrace();
        }
        return detail;
    }
}
